package com.hltx.controller.pay;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.constants.CommonConstant;
import com.hltx.constants.GoodsConstant;
import com.hltx.constants.PayConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.address.Address;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.goods.GoodsOrder;
import com.hltx.pojo.pay.OrderAddress;
import com.hltx.pojo.pay.OrderInfo;
import com.hltx.pojo.pay.PayInfo;
import com.hltx.pojo.pay.PayInfoAlipay;
import com.hltx.pojo.pay.PayOrder;
import com.hltx.pojo.ratioconfigure.RatioConfigure;
import com.hltx.pojo.user.User;
import com.hltx.service.adress.AddressManager;
import com.hltx.service.alipay.AlipayConfigs;
import com.hltx.service.brokerage.impl.ConsumeBrokerageV2Service;
import com.hltx.service.goods.GoodsManager;
import com.hltx.service.pay.AlipayPayManager;
import com.hltx.service.pay.PayManager;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DataUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;





/**
 * 确认支付controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/pay")
public class PayHandelController extends BaseController{

	@Autowired
	private AddressManager addressService;
	
	@Autowired
	private PayManager payService;
	
	@Autowired
	private AlipayPayManager alipayPayService;
	
	@Autowired
	private GoodsManager goodsService;
	
	@Autowired
	private UserManager userService;
	
	@Autowired
	private ConsumeBrokerageV2Service brokerageV2Service;
	
	@Value("${pay.version}")
	private boolean version;
	@Value("${pay.wx.money}")
	private String xwMoney;
	@Value("${pay.al.money}")
	private String alMoney;
	
	@RequestMapping(value="/confirm_balance_pay",method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String, Object> confirmBalancePay(PayInfo pi, HttpSession session, HttpServletRequest request){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = (User) session.getAttribute(
				"sessionUser");
		int res = validateParams(pi, user, resMap);
		
		if(res == 0){
			//生成订单信息
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("orderMap", resMap.get("orderMap"));
			params.put("oa", resMap.get("oa"));
			params.put("goList", resMap.get("goList"));
			params.put("cbi", resMap.get("cbi"));
			params.put("pi", pi);
			
			ResultInfo resInfo = payService.cbalancePayOrder(params);
	
			resMap.put("result", resInfo);
			if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){
				resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				brokerageV2Service.bounsShunt(pi.getId());
			}
		}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;
	}
	
	/**
	 * 微信JS支付
	 * 
	 * @return
	 */
	@RequestMapping(value = "/confirm_wxjs_pay", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getWxJsApiCode(PayInfo pi,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			User user = (User) session.getAttribute(
					"sessionUser");
			String openId = (String)session.getAttribute(CommonConstant.OPEN_KEY);
			if(StringUtils.isEmpty(openId)){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "OPENID_NULL", "请在使用微信打开商城",null));
				return resMap;
			}else{
				pi.setOpenId(openId);
			}
			int res = validateParams(pi, user, resMap);

			if(res == 0){
				//微信支付			
				Map<String,Object> params = new HashMap<String, Object>();
				params.put("pi", pi);
				params.put("orderMap", resMap.get("orderMap"));
				params.put("oa", resMap.get("oa"));
				params.put("goList", resMap.get("goList"));
				params.put("contextPath", request.getContextPath());
				Map<String, Object> saveRes = payService.saveWxPayOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}

			}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));

		}
		return resMap;
	}
	
	/**
	 * 微信APP支付
	 * 
	 * @return
	 */
	@RequestMapping(value = "/confirm_app_pay", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getWxAppApiCode(PayInfo pi,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			User user = (User) session.getAttribute(
					"sessionUser");
			int res = validateParams(pi, user, resMap);

			if(res == 0){
				//微信支付			
				Map<String,Object> params = new HashMap<String, Object>();
				params.put("pi", pi);
				params.put("orderMap", resMap.get("orderMap"));
				params.put("oa", resMap.get("oa"));
				params.put("goList", resMap.get("goList"));
				params.put("contextPath", request.getContextPath());
				Map<String, Object> saveRes  = payService.saveWxAppPayOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}

			}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));

		}
		return resMap;
	}
	
	
	/**
	 * 待付款订单微信支付
	 * @param orderCode
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/confirm_wxjs_unpaid", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> wxWapNnpay(String orderCode,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			String openId = (String)session.getAttribute(CommonConstant.OPEN_KEY);
			if(StringUtils.isEmpty(openId)){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "OPENID_NULL", "请在使用微信打开商城",null));
				return resMap;
			}
			
			int len = StringUtils.length(orderCode);
			long orderId = Long.parseLong(orderCode.substring(4, len - 7));
			PayOrder payOrder = payService.getPayOrderInfo(orderId);
			if(payOrder == null){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("orderId", orderId);
				params.put("contextPath", request.getContextPath());
				params.put("openId", openId);
				Map<String, Object> saveRes = payService.saveWaitWXOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					PayInfo pi = (PayInfo) saveRes.get("pi");
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}else{
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("contextPath", request.getContextPath());
				params.put("openId", openId);
				params.put("payOrder", payOrder);
				Map<String, Object> saveRes = payService.saveWaitWXExistOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					PayInfo pi = (PayInfo) saveRes.get("pi");
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;
	}
	
	/**
	 * 待付款订单微信支付
	 * @param orderCode
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/confirm_wxapp_unpaid", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> wxAppNnpay(String orderCode,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			int len = StringUtils.length(orderCode);
			long orderId = Long.parseLong(orderCode.substring(4, len - 7));
			PayOrder payOrder = payService.getPayOrderInfo(orderId);
			if(payOrder == null){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("orderId", orderId);
				params.put("contextPath", request.getContextPath());
				params.put("paySource", PayConstant.PAY_TAG_APP);
				Map<String, Object> saveRes = payService.saveWaitWXOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					PayInfo pi = (PayInfo) saveRes.get("pi");
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}else{
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("contextPath", request.getContextPath());
				params.put("payOrder", payOrder);
				Map<String, Object> saveRes = payService.saveAppWaitWXExistOrder(params);
				if(saveRes.containsKey("prePayInfo")){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("prePayInfo", saveRes.get("prePayInfo"));
					PayInfo pi = (PayInfo) saveRes.get("pi");
					resMap.put("payCode",pi.getCodePre()+pi.getId()+pi.getCodeSuf());
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;
	}
	
	/**
	 * 支付宝手机网站支付
	 * @param pi
	 * @param request
	 * @param session
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/confirm_alipay_pay", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> alipayWapPay(PayInfo pi,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute("sessionUser");
			
			int res = validateParams(pi, user, resMap);

			if (res == 0) {
				// 支付宝支付
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("pi", pi);
				params.put("orderMap", resMap.get("orderMap"));
				params.put("oa", resMap.get("oa"));
				params.put("goList", resMap.get("goList"));
				Map<String, Object> saveRes = payService.saveAlipayPayOrder(params);
				Map<String, String> returnParams = (Map<String, String>) saveRes.get("returnParams");
				String contextPath = request.getContextPath();
				String url = alipayPayService.alipayWap(returnParams, contextPath);

				if (StringUtils.isNotEmpty(url)) {
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("url", url);
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;

	}
	

	/**
	 * 待付款订单支付
	 * @param pi
	 * @param request
	 * @param session
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/confirm_alipay_unpaid", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> alipayWapNnpay(String orderCode,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			int len = StringUtils.length(orderCode);
			long orderId = Long.parseLong(orderCode.substring(4, len - 7));
			PayOrder payOrder = payService.getPayOrderInfo(orderId);
			if(payOrder == null){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("orderId", orderId);
				Map<String, Object> saveRes = payService.saveWaitAlipayOrder(params);
				Map<String, String> returnParams = (Map<String, String>) saveRes.get("returnParams");
				String contextPath = request.getContextPath();
				String url = alipayPayService.alipayWap(returnParams, contextPath);

				if (StringUtils.isNotEmpty(url)) {
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("url", url);
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}
			}else{
				List<GoodsOrder> goodsOrder = payService.getGoodsOrderByOrderId(orderId);
				String title = goodsOrder.get(0).getTitle();
				if(goodsOrder.size() > 1){
					title = title + "等";
				}
				
//			
//				OrderInfo orderInfo = payService.getOrderInfoByOId(orderId);
//				BigDecimal realPrice = DataUtil.getBigDecimal(orderInfo.getRealPrice());//orderInfo.getRealPrice();
//				
				long payId = payOrder.getPayId();
				PayInfo pi = payService.getPayInfoByPid(payId);
				PayInfoAlipay payInfoAlipay = payService.getPayInfoAlipayBypId(payId);
				if(payInfoAlipay == null){
					// 生成支付附记录-支付宝
					payInfoAlipay = new PayInfoAlipay();
					payInfoAlipay.setPayId(pi.getId());
					if (version) {
						payInfoAlipay.setTotalAmount(alMoney);
					}else{
						payInfoAlipay.setTotalAmount(pi.getAddPrice().toString());
					}
					payInfoAlipay.setTimeStart(DateUtil.getTime());
					payInfoAlipay.setSellerId(AlipayConfigs.sellerId);
					payService.insertPayInfoAlipay(payInfoAlipay);
				}
				BigDecimal realPrice = DataUtil.getBigDecimal(payInfoAlipay.getTotalAmount());
				
				Map<String, String> returnParams = new HashMap<String, String>();
				returnParams.put("outTradeNo", pi.getCodePre() + payId + pi.getCodeSuf());
				returnParams.put("subject", title);
				returnParams.put("totalAmount", payInfoAlipay.getTotalAmount());
				returnParams.put("body", "共花费金额" + realPrice + "元");
				String contextPath = request.getContextPath();
				String url = alipayPayService.alipayWap(returnParams, contextPath);

				if (StringUtils.isNotEmpty(url)) {
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("url", url);
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail","系统繁忙", null));
				}

			}
			
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;

	}
	
	
	public int validateParams(PayInfo pi, User user, Map<String, Object> resMap) throws Exception{
		
		//验证用户是否登录
		if(user == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "LOGIN_OUT", "用户未登录","/toLogin"));
			return 1;
		}
		
		//判断金额是否正确
		BigDecimal totalPrice = DataUtil.getBigDecimal(pi.getTotalPrice(),2);
		BigDecimal descountTotalPrice = DataUtil.getBigDecimal(pi.getDescountTotalPrice(),2);
		BigDecimal balancePrice = DataUtil.getBigDecimal(pi.getBalancePrice(),2);
		BigDecimal addPrice = DataUtil.getBigDecimal(pi.getAddPrice(),2);
		BigDecimal totalPointsPrice = DataUtil.getBigDecimal(pi.getTotalPointsPrice(),2);
		BigDecimal totalCashBackPrice = DataUtil.getBigDecimal(pi.getTotalCashBackPrice(),2);
		int totalPointsNum = pi.getTotalPointsNum();
		if(descountTotalPrice.compareTo(BigDecimal.ZERO) < 0 
				|| balancePrice.compareTo(BigDecimal.ZERO) < 0 
				|| addPrice.compareTo(BigDecimal.ZERO) < 0
				|| totalPointsPrice.compareTo(BigDecimal.ZERO) < 0
				|| totalPointsNum < 0 ){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
			return 1;
		}
		BigDecimal realTotalPrice = BigDecimal.ZERO;
		String payMode = pi.getPayMode();
		if(StringUtils.equals(payMode, "YE")){
			realTotalPrice = balancePrice.add(totalPointsPrice);
			if(addPrice.compareTo(BigDecimal.ZERO) != 0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
				return 1;
			}
		}else if(StringUtils.equals(payMode, "JF")){
			realTotalPrice = totalPointsPrice;
			if(totalPointsPrice.compareTo(DataUtil.getBigDecimal(user.getPoints())) != -1){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "POINTS_LOSE", "兑换券不足不能余额支付",null));
				return 1;
			}
			if(addPrice.compareTo(BigDecimal.ZERO) > 0 || balancePrice.compareTo(BigDecimal.ZERO)>0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
				return 1;
			}
		}else if(StringUtils.equals(payMode, "WX")){
			realTotalPrice = balancePrice.add(addPrice).add(totalPointsPrice);
		}else if(StringUtils.equals(payMode, "ZFB")){
			realTotalPrice = balancePrice.add(addPrice).add(totalPointsPrice);
		}
		
		
		if(totalPrice.compareTo(realTotalPrice) != 0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
			return 1;
		}

		//检查用户余额
		user = userService.getUser(user);
		BigDecimal userBalance = DataUtil.getBigDecimal(user.getBalance());
		if(userBalance.compareTo(balancePrice)<0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "BALANCE_LOSE", "余额不足",null));
			return 1;
		}
		//检查用户积分
		int userPoints = user.getPoints();
		if(userPoints < totalPointsNum){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "POINTS_LOSE", "兑换券不足",null));
			return 1;
		}
		//判断是否是VIP用户
		//int level = CustomUtil.strToInt(user.getLevel());
//		if(level <= 0){
//			if(totalPointsNum >0){
//			resMap.put("result", this.initResult(ResultInfo.ERROR, "POINTS_LOSE", "非VIP用户",null));
//			return 1;
//			}
//		}
		
		//收货地址验证
		int addressId = pi.getAddressId();
		if(addressId <=0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "ADDRESS_LOSE", "请选择收货地址",null));
			return 1;
		}
		Page page = new Page();
		page.getParams().put("id", addressId);
		Address address = addressService.findAddressByID(page);
		if(address == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "POINTS_LOSE", "请选择收货地址",null));
			return 1;
		}
		
		//参数验证
		String type = pi.getType();
		if(!(StringUtils.equals("buy_now", type) || StringUtils.equals("confirm_shopCart", type))){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PARAMS_ERROR", "参数有误",null));
			return 1;
		}
		
		int[] goodsIds = pi.getGoodsIds();
		int[] buyNums = pi.getBuyNums();
		int[] isPointsBuys = pi.getIsPointsBuys();
		String[] specs = pi.getSpecs();
		if(goodsIds.length == 0||buyNums.length == 0 || isPointsBuys.length ==0 || specs.length ==0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PARAMS_ERROR", "参数有误",null));
			return 1;
		}
		realTotalPrice = BigDecimal.ZERO;
		//BigDecimal weight = BigDecimal.ZERO;
		//BigDecimal orderWeight = BigDecimal.ZERO;
		BigDecimal transit = BigDecimal.ZERO;
		BigDecimal realTotalCashBackPrice = BigDecimal.ZERO;
		//BigDecimal vipPrice = BigDecimal.ZERO;
		int realTotalPointsNum = 0;
		List<GoodsOrder> goList = new ArrayList<GoodsOrder>();
		RatioConfigure ratioConfigure = payService.getRatioConfigure();
		int changePoints;
		BigDecimal changePrice;
		Map<String, Object> orderMap = new HashMap<String, Object>();
		for(int i=0; i<goodsIds.length; i++){
			int gId = goodsIds[i];
			List<GoodsOrder> goods = goodsService.getGoodsListByGid(gId);
			if(goods == null || goods.size() == 0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "GOODS_NULL", "商品已下架",null));
				return 1;
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("curTime", DateUtil.getTime());
			params.put("goodsId", gId);
			GoodsOrder go = goods.get(0);
			String supplierId = go.getSupplierId();
			//是否活动促销
			
			if(StringUtils.equals(go.getIsSales(),"01")){
		
				Map<String, Object> goodsSales = goodsService.getGoodsSalesByGId(params);
				if(goodsSales == null){
					go.setIsSales("00");
				}else{
					go.setSalesName((String)goodsSales.get("salesName"));
				}
				
			} 
			//判断商品规格
			Map<String, Object> goodsSpec = null;
			go.setSpec(CustomUtil.toReplaceSpec(specs[i], "#", ","));
			if(StringUtils.equals(go.getIsSelectSpec(), GoodsConstant.SELECT_SPEC_YES)){
				if(StringUtils.equals(go.getSpec(), "0")){
					resMap.put("result", this.initResult(ResultInfo.ERROR, "SPEC_ERROR", "规格错误",null));
					return 1;
				}
				params.put("spec", go.getSpec());
				goodsSpec = goodsService.getGoodsSpecBySpec(params);
				if(goodsSpec == null){
					resMap.put("result", this.initResult(ResultInfo.ERROR, "SPEC_ERROR", "规格错误",null));
					return 1;
				}
				List<Map<String, Object>> goodsSpecPro = goodsService.getGoodsSpecInfoBySpec(params);
				//封装规格描述
				StringBuffer specDesc = new StringBuffer();;
				for(Map<String, Object> spec : goodsSpecPro){
					specDesc.append(spec.get("labelName")).append(":").append(spec.get("attrName")).append(";");
				}
				go.setSpecDesc(specDesc.toString());
				go.setPrice(DataUtil.getBigDecimal(goodsSpec.get("price"),2));
				go.setBidPrice(DataUtil.getBigDecimal(goodsSpec.get("bidPrice"),2));
				go.setRealPrice(DataUtil.getBigDecimal(goodsSpec.get("salesPrice"),2));

			}	
			go.setBuyNum(buyNums[i]);
			BigDecimal maxRatio = ratioConfigure.getMaxRatio();
			BigDecimal minRatio = ratioConfigure.getMinRatio();
			BigDecimal goodsDescount = BigDecimal.ZERO;
			int buyNum = go.getBuyNum();
			changePoints = 0;
			changePrice = BigDecimal.ZERO;
			if(StringUtils.equals(go.getIsSales(),"01")){
				goodsDescount = go.getBidPrice().multiply(DataUtil.getBigDecimal(10)).divide(go.getMarketPrice(), 2 , BigDecimal.ROUND_HALF_DOWN) ;
				if(goodsDescount.compareTo(minRatio)>0 && goodsDescount.compareTo(maxRatio)<=0) {
					changePoints = CustomUtil.requiredIntegral(DataUtil.getBigDecimal(go.getRealPrice(),2), goodsDescount, minRatio) * buyNum;
					changePrice = CustomUtil.requiredPrice(DataUtil.getBigDecimal(go.getRealPrice(),2), goodsDescount, minRatio).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
					realTotalPrice = realTotalPrice.add(changePrice);
				}else if(goodsDescount.compareTo(minRatio)<=0){
					changePoints = go.getRealPrice().setScale(0, BigDecimal.ROUND_CEILING).intValue();
				}else{
					changePrice = DataUtil.getBigDecimal(go.getRealPrice(),2).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
					realTotalPrice = realTotalPrice.add(changePrice);
				}
				//realTotalPrice = realTotalPrice.add(DataUtil.getBigDecimal(go.getRealPrice(),2).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
			}else{
				go.setRealPrice(go.getPrice());
				goodsDescount = go.getBidPrice().multiply(DataUtil.getBigDecimal(10)).divide(go.getMarketPrice(), 2 , BigDecimal.ROUND_HALF_DOWN) ;
				if(goodsDescount.compareTo(minRatio)>0 && goodsDescount.compareTo(maxRatio)<=0) {
					changePoints = CustomUtil.requiredIntegral(DataUtil.getBigDecimal(go.getRealPrice(),2), goodsDescount, minRatio) * buyNum;
					changePrice = CustomUtil.requiredPrice(DataUtil.getBigDecimal(go.getRealPrice(),2), goodsDescount, minRatio).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
					realTotalPrice = realTotalPrice.add(changePrice);
				}else if(goodsDescount.compareTo(minRatio)<=0){
					changePoints = go.getRealPrice().setScale(0, BigDecimal.ROUND_CEILING).intValue();
				}else{
					changePrice = DataUtil.getBigDecimal(go.getRealPrice(),2).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
					realTotalPrice = realTotalPrice.add(changePrice);
				}
			}
			realTotalPointsNum +=changePoints;
			go.setUsePointsNum(changePoints);
			go.setUsePrice(changePrice);
			//if(level > 0){
			
//			if(isPointsBuys[i] == 1){
//				if(!(StringUtils.equals(go.getIsVipFullback(), GoodsConstant.VIP_BACK_YES) 
//						&& StringUtils.equals(go.getIsPointsBuy(), GoodsConstant.POINTS_BUY_YES))){
//					resMap.put("result", this.initResult(ResultInfo.ERROR, "POINTS_ERROR", "不能积分换购",null));
//					return 1;
//				}
//				realTotalPointsNum +=go.getPointsNum() * go.getBuyNum();
//				go.setUsePointsNum(go.getPointsNum());
//				
//			}else{		
//				if(StringUtils.equals(go.getIsVipFullback(), GoodsConstant.VIP_BACK_YES)){
//					realTotalCashBackPrice = realTotalCashBackPrice.add(DataUtil.getBigDecimal(go.getReturnAmount(),2).multiply(DataUtil.getBigDecimal(go.getBuyNum())));		
//					vipPrice = vipPrice.add(DataUtil.getBigDecimal(go.getRealPrice(),2).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
//				}	
//			}
			//}
			
			BigDecimal transitPrice = BigDecimal.ZERO;
			//weight = weight.add(DataUtil.getBigDecimal(go.getWeight()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
			transit = transit.add(DataUtil.getBigDecimal(go.getTransitPrice()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
			//orderWeight = DataUtil.getBigDecimal(go.getWeight()).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
			transitPrice = DataUtil.getBigDecimal(go.getTransitPrice()).multiply(DataUtil.getBigDecimal(go.getBuyNum()));
			go.setMaxRatio(maxRatio);
			go.setDiscount(goodsDescount);
			go.setSupplierId(supplierId);
			if(orderMap.containsKey(supplierId)){
				OrderInfo oi = (OrderInfo)orderMap.get(supplierId);
				oi.setCodePre(DateUtil.getYear());
				oi.setCodeSuf(CustomUtil.codeSuf(3, user.getId()));
				oi.setCode(oi.getCodePre()+oi.getCodeSuf());
				oi.setUserId(user.getId());
				oi.setUsePoints(oi.getUsePoints() + changePoints);
				oi.setRealPrice(changePrice.add(transitPrice).add(oi.getRealPrice()));
				oi.setTotalPrice(oi.getRealPrice().add(DataUtil.getBigDecimal(oi.getUsePoints())));
				oi.setTransitPrice(transitPrice.add(oi.getTransitPrice()));
				oi.setLine(pi.getLine());
				oi.setTag(pi.getTag());
				oi.setCreateTime(DateUtil.getTime());
				oi.setCurPayPoints(oi.getUsePoints());
				oi.setCurPayPrice(oi.getRealPrice());
				orderMap.put(supplierId, oi);
			}else{
				OrderInfo oi = new OrderInfo();
				oi.setCodePre(DateUtil.getYear());
				oi.setCodeSuf(CustomUtil.codeSuf(3, user.getId()));
				oi.setCode(oi.getCodePre()+oi.getCodeSuf());
				oi.setUserId(user.getId());
				oi.setUsePoints(changePoints);
				oi.setRealPrice(changePrice.add(transitPrice));
				oi.setTotalPrice(oi.getRealPrice().add(DataUtil.getBigDecimal(oi.getUsePoints())));
				oi.setTransitPrice(transitPrice);
				oi.setLine(pi.getLine());
				oi.setTag(pi.getTag());
				oi.setCreateTime(DateUtil.getTime());
				oi.setCurPayPoints(changePoints);
				oi.setCurPayPrice(oi.getRealPrice());
				orderMap.put(supplierId, oi);
			}
			
			goList.add(go);
		}
		//汇总数据，计算运费
		//transit = weight.multiply(DataUtil.getBigDecimal(CourierConstant.WEIGHT_UNIT_PRICE));
		realTotalPrice = realTotalPrice.add(transit);
		if(descountTotalPrice.compareTo(realTotalPrice) != 0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
			return 1;
		}
		
		if(realTotalPointsNum != totalPointsNum){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "兑换券有误",null));
			return 1;
		}
		
		//判断返现金额是否正确
		if(totalCashBackPrice.compareTo(realTotalCashBackPrice)!=0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "返现金额有误",null));
			return 1;
		}
		//返现记录
//		if(totalCashBackPrice.compareTo(BigDecimal.ZERO) > 0){
//			CashBackInfo cbi = new CashBackInfo();
//			cbi.setUserId(user.getId());
//			cbi.setState(CommonConstant.HANDEL_NO);
//			cbi.setMoney(totalCashBackPrice);
//			cbi.setStartTime(DateUtil.getTime());
//			cbi.setEndTime(DateUtil.getAfterDayDate(cbi.getStartTime(), PayConstant.DEFAULT_CASHBACK_DAYS,1));
//			cbi.setCashbackTime(DateUtil.getAfterDayDate(cbi.getStartTime(), PayConstant.DEFAULT_CASHBACK_DAYS + 1,0));
//			cbi.setCreateTime(DateUtil.getTime());
//			cbi.setUpdateTime(DateUtil.getTime());
//			resMap.put("cbi", cbi);
//		}
		
		//封装对象
		pi.setCodePre(DateUtil.getYear());
		pi.setCodeSuf(CustomUtil.codeSuf(3, user.getId()));
		pi.setUserId(user.getId());
		pi.setUserLevel(user.getLevel());
//		OrderInfo oi = new OrderInfo();
//		oi.setCodePre(DateUtil.getYear());
//		oi.setCodeSuf(CustomUtil.codeSuf(3, user.getId()));
//		oi.setCode(oi.getCodePre()+oi.getCodeSuf());
//		oi.setUserId(user.getId());
//		oi.setUsePoints(totalPointsNum);
//		oi.setTotalPrice(totalPrice);
//		oi.setTransitPrice(transit);
//		oi.setRealPrice(balancePrice.add(addPrice));
//		oi.setLine(pi.getLine());
//		oi.setTag(pi.getTag());
//		oi.setCreateTime(DateUtil.getTime());
//		oi.setCurPayPoints(totalPointsNum);
//		oi.setCurPayPrice(oi.getRealPrice());
//		oi.setVipPrice(vipPrice);
		
		OrderAddress oa = new OrderAddress();
		oa.setProvinceId(address.getProvinceID());
		oa.setCityId(address.getCityID());
		oa.setCountryId(address.getCountryID());
		oa.setReceiverName(address.getReceiverName());
		oa.setReceiverPhone(address.getReceiverPhone());
		oa.setReceiverAddress(address.getReceiverAddress());
		
		resMap.put("orderMap", orderMap);
		resMap.put("oa", oa);
		resMap.put("goList", goList);
		return 0;
	}

	
	@RequestMapping(value="/cCancelOrder",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> cCancelOrder(PayInfo pi, HttpSession session, HttpServletRequest request){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = (User) session.getAttribute(
				"sessionUser");
		//验证用户是否登录
		if(user == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "LOGIN_OUT", "用户未登录","/toLogin"));
		}else{
			//取消订单
			String id=request.getParameter("orderID");
			long orderID=Long.parseLong(id.substring(4,id.length()-7));
			
			ResultInfo resInfo = payService.cOrderRefund(orderID);
			resMap.put("result", resInfo);
		}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;
	}
	
	@RequestMapping(value="/cCancelWaitOrder",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> cCancelWaitOrder(HttpSession session, HttpServletRequest request){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = (User) session.getAttribute(
				"sessionUser");
		//验证用户是否登录
		if(user == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "LOGIN_OUT", "用户未登录","/toLogin"));
		}else{
			//取消订单
			String id=request.getParameter("orderID");
			long orderId=Long.parseLong(id.substring(4,id.length()-7));
			
			ResultInfo resInfo = payService.cOrderWaitRefund(orderId);
			resMap.put("result", resInfo);
		}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", null));
		}
		return resMap;
	}
	
}
